<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\others\UploadFileController;
use App\models\user\Roles;
use App\models\user\User;
use App\other\AdminFlag;
use App\other\UtilsClass;
use Auth;
use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Validator;
use Illuminate\Support\Str as Strings;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware(['admin:' . AdminFlag::ADMIN_FLAG_USER]);
    }

    public function user()
    {
        return view('admin.user');
    }

    public function userList(Request $request)
    {
        $q = $request->get('q');
        if (!empty($q)) {
            $seach = '%' . $q . '%';
            $users = User::where('name', 'like', $seach)->orwhere('email', 'like', $seach)->paginate(30);
        } else {
            $users = User::where('id', '>', 0)->paginate(30);
        }
//        dd($users->items()[0]->roleLevel());
        return view('admin.user.list', compact('users', 'q'));
    }

    public function userEdit(Request $request)
    {
        $user = null;
        $id = $request->get('id');
        if (!empty($id) && is_numeric($id)) {
            $user = User::find($id);
            if (empty($user) || $user->userRole->role->level >= Auth::user()->userRole->role->level) {
                $user = null;
            }
        }
        $roles = Roles::where('level', '<', Auth::user()->userRole->role->level)->get();
        return view('admin.user.edit', compact('user', 'roles'));
    }

    public function userEditUpdate(Request $request)
    {
        $v = Validator::make($request->all(), [
            'uid'           => 'required|integer|exists:users,id',
            'name'          => 'required|max:16',
            'password'      => 'min:8|max:64',
            'email'         => 'required|email|max:64',
            'truename'      => 'max:32',
            'city'          => 'max:32',
            'company'       => 'max:32',
            'weiboname'     => 'max:32',
            'weibourl'      => 'url|max:255',
            'weblink'       => 'url|max:255',
            'profile'       => 'file',
            'wechatqrcode'  => 'file',
            'paymentqrcode' => 'file',
            'introduction'  => 'max:255',
            'role_id'       => 'required|integer|exists:roles,id',
            'verified'      => 'max:3',
//            'ban_time'      => 'integer',
            'bind_steam'    => 'max:3'
        ]);

        if ($v->fails()) {
            return redirect()
                ->back()->with('er', UtilsClass::arrayToStringForItem($v->getMessageBag()->getMessages()));
        }
        $user = User::find($request->get('uid'));

        if ($user->userRole->role->level >= Auth::user()->userRole->role->level) {
            return redirect()->back()->with('er', '无法编辑此用户');
        }
        $input = $request->all();
        $deleteSession = false;
        if ($input['name'] != $user->name) {
            $tem = User::where('name', $input['name'])->get();
            if (count($tem)) {
                if (!empty(User::where('email', $request->get('email'))->first())) {
                    return redirect()
                        ->back()
                        ->with(['er' => '名称已存在']);
                }
            }
            $user->name = $request->get('name');
        }
        if ($user->email != $input['email']) {
            if (!empty(User::where('email', $request->get('email'))->first())) {
                return redirect()
                    ->back()
                    ->withErrors(['email' => '邮箱已存在'])
                    ->withInput($request->all());
            }
            $user->email = $input['email'];
            $user->verified = 0;
            $deleteSession = true;
            if (empty($request->get('verified'))) {
                RegisterController::sendRegisterEmail($user);
            }
        }
        if ($request->file('wechatqrcode') != null) {
            $wechatqrcode = UploadFileController::getImgPateh($request, 'wechatqrcode');
            if ($wechatqrcode != -1) {
                $user->wechatqrcode = $wechatqrcode;
            }
        }
        if ($request->file('profile') != null) {
            $profile = UploadFileController::getImgPateh($request, 'profile');
            if ($profile != -1) {
                $user->profile = $profile;
            }
        }
        if ($request->file('paymentqrcode') != null) {
            $paymentqrcode = UploadFileController::getImgPateh($request, 'paymentqrcode');
            if ($paymentqrcode != -1) {
                $user->paymentqrcode = $paymentqrcode;
            }
        }
        $user->truename         = $input['truename'];
        $user->city             = $input['city'];
        $user->company          = $input['company'];
        $user->weiboname        = $input['weiboname'];
        $user->weblink          = $input['weblink'];
        $user->weibourl         = $input['weibourl'];
        $user->introduction     = $input['introduction'];

        if (!empty($request->get('password'))) {
            $user->password = bcrypt($request->get('password'));
            $deleteSession = true;
        }
        if (!empty($request->get('verified'))) {
            $user->verified = 1;
        } else {
            $user->verified = 0;
            $deleteSession = true;
        }
        if (!empty($input['ban_time']) && is_numeric($input['ban_time'])){
            $time = intval($input['ban_time']);
            if ($time === 9999){
                $user->is_ban       = -1;
            }else if($time === 7777){
                $user->is_ban       = 0;
            }else{
                $user->is_ban = 1;
            }
            $user->ban_time         = time()+$time;
            $deleteSession          = true;
        }

        if (!empty($input['bind_steam']) && $input['bind_steam'] == 'on'){
            if (!empty($user->getSteamUser)){
                $user->steam->delete();
            }
        }
        if ($deleteSession == true) {
            $user->deleteUserSession();
        }
        $userRole = $user->userRole;
        $role = Roles::find($input['role_id']);
        if (Auth::user()->userRole->role->level > $role->level){
            $userRole->role_id = $input['role_id'];
        }else{
            return redirect()->back()->with('erorr', 'Role错误');
        }

        DB::transaction(function () use ($userRole, $user){
            $userRole->save();
            $user->save();
        });
        return redirect()->back()->with(['success' => '保存成功']);
    }

    public function role()
    {
        return view('admin.user.role');
    }

    public function roleGet()
    {
        if (Auth::user()->roleLevel() == 100) {
            $roles = Roles::all();
        } else {
            $roles = Roles::where('level', '<', Auth::user()->roleLevel())->get();
        }
        return ['data' => $roles, 'files' => '', 'options' => ''];
    }

    public function roleEdit(Request $request){
        $this->validate($request, [
            'action' => 'required'
        ]);
        $input = $request->all();
        if ($input['action'] === 'create' || $input['action'] === 'edit') {
            $validate = Validator::make($input, [
                'id' => 'integer|exists:roles,id',
                'data.name' => 'required|max:32',
                'data.display_name' => 'required|max:64',
                'data.description' => 'required|max:64',
                'data.flag' => 'required|integer',
                'data.level' => 'required|integer'
            ]);

            if ($validate->fails()) {
                $error = $validate->getMessageBag()->getMessages();
                $fieldErrors = array();
                foreach ($error as $k => $v) {
                    $key = str_replace('data.', '', $k);
                    $f = array();
                    $f['name'] = $key;
                    $f['status'] = $v;
                    array_push($fieldErrors, $f);
                }
                return ['fieldErrors' => $fieldErrors];
            }
            $role = new Roles();
            if ($input['action'] === 'edit') {
                $role = Roles::find($input['id']);
            }
            $role->name = $input['data']['name'];
            $role->display_name = $input['data']['display_name'];
            $role->description = $input['data']['description'];
            $role->flag = $input['data']['flag'];
            $role->level = $input['data']['level'];
            $role->save();
            return [
                'data' =>
                [
                    'id'            => $role->id,
                    'name'          => $role->name,
                    'display_name'  => $role->display_name,
                    'description'   => $role->description,
                    'flag'          => $role->flag,
                    'level'         => $role->level,
                    'created_at'    => $role->created_at
                ]
            ];
        }
        if ($input['action'] === 'remove'){
//            dd($input[]);
            $validate = Validator::make($input, [
                'data' => 'required|array',
            ]);

            if ($validate->fails()) {
                return ['error' => 'id不存现在'];
            }
            foreach ($input['data'] as $role_id){
                $temp = Roles::find($role_id);
                if (!empty($temp) && $temp->has_del == 1){
                    $temp->changUserRole($temp->id);
                    Roles::destroy($temp->id);
                }
            }
            return ['data' => []];
        }
        return 0;
    }
}
